package product

import (
	"API/client"
	"API/request"
	"API/response"
	"common/utils"
	"github.com/gin-gonic/gin"
	product "product_server/proto"
)

func CreateGroup(c *gin.Context) {
	var req request.CreateGroupRequest
	if err := c.ShouldBind(&req); err != nil {
		response.CurrencyErrResponse(c, 400, err.Error())
		return
	}
	userId := c.GetUint("userId")
	res, err := client.CreateGroup(c, &product.CreateGroupRequest{
		Uid:       int64(userId),
		ProductId: req.ProductId,
	})
	if err != nil {
		response.CurrencyErrResponse(c, -1, utils.CutOutRpcError(err.Error()))
		return
	}
	response.CurrencySuccessResponse(c, "拼团成功", map[string]interface{}{"token": res.Token})
}

func GetGroupDetail(c *gin.Context) {
	var req request.GetGroupDetailRequest
	if err := c.ShouldBind(&req); err != nil {
		response.CurrencyErrResponse(c, 400, err.Error())
		return
	}

	res, err := client.GetGroupDetail(c, &product.GetGroupDetailRequest{
		GroupId: req.GroupId,
	})
	if err != nil {
		response.CurrencyErrResponse(c, -1, utils.CutOutRpcError(err.Error()))
		return
	}
	response.CurrencySuccessResponse(
		c,
		"获取成功",
		map[string]interface{}{
			"data": res,
		},
	)
}

func ParseTaoBao(c *gin.Context) {
	var req request.ParseTaoBaoRequest
	if err := c.ShouldBind(&req); err != nil {
		response.CurrencyErrResponse(c, 400, err.Error())
		return
	}

	res, err := client.ParseTaoBao(c, &product.ParseTaoBaoRequest{
		TaobaoUrl: req.TaoBaoUrl,
	})
	if err != nil {
		response.CurrencyErrResponse(c, -1, utils.CutOutRpcError(err.Error()))
		return
	}
	response.CurrencySuccessResponse(
		c,
		"success",
		map[string]interface{}{
			"data": res,
		},
	)
}

func JoinGroup(c *gin.Context) {
	var req request.JoinGroupRequest
	if err := c.ShouldBind(&req); err != nil {
		response.CurrencyErrResponse(c, 400, err.Error())
		return
	}

	userId := c.GetUint("userId")

	res, err := client.JoinGroup(c, &product.JoinGroupRequest{
		Uid:     int64(userId),
		GroupId: req.GroupId,
	})
	if err != nil {
		response.CurrencyErrResponse(c, -1, utils.CutOutRpcError(err.Error()))
		return
	}
	response.CurrencySuccessResponse(
		c,
		"success",
		map[string]interface{}{
			"data": res,
		},
	)
}
